// 可见性引擎 - 处理题目可见性逻辑
import { getFact } from './facts-manager.js'

/**
 * 评估可见性条件
 * @param {Object} condition - 可见性条件
 * @param {Array} answers - 当前答案数组
 * @returns {boolean} 是否可见
 */
const evaluateVisibleWhen = (condition, answers) => {
    if (!condition) return true;

    const getFactValue = (key) => {
        try {
            return getFact(key);
        } catch (e) {
            console.warn(`Failed to get fact value for key: ${key}`, e);
            return undefined;
        }
    }

    const judgeAnswer = (value, id) => {
        if (Array.isArray(value)) {
            return answers[id] && value.includes(answers[id]);
        }
        return answers[id] === value;
    }

    // 支持 and/or/not 逻辑
    if (condition.and) {
        return condition.and.every(c => evaluateVisibleWhen(c, answers));
    }

    if (condition.or) {
        return condition.or.some(c => evaluateVisibleWhen(c, answers));
    }

    if (condition.not) {
        return !evaluateVisibleWhen(condition.not, answers);
    }

    // 基础条件类型
    if (condition.answerEquals) {
        const { questionId, value } = condition.answerEquals;
        return judgeAnswer(value, questionId);
    }

    if (condition.factEquals) {
        const { factId, value } = condition.factEquals;
        const factValue = getFactValue(factId);
        return factValue === value;
    }

    return true;
}

/**
 * 获取有效题目ID
 * @param {Array} ids - 题目ID数组
 * @param {Array} filters - 过滤条件数组
 * @param {Array} answers - 当前答案数组
 * @param {Object} questions - 题目对象
 * @returns {Array} 有效题目ID数组
 */
export const getValidQuestionIds = (ids, filters, answers, questions) => {
    if (!ids || !Array.isArray(ids)) return [];
    
    return ids.filter((id) => {
        const item = questions[id];

        for (const filter of filters) {
            switch (filter) {
                case "visible":
                    if (item.visibleWhen && !evaluateVisibleWhen(item.visibleWhen, answers)) {
                        return false;
                    }
                    break;
                case "plain":
                    if (item.type === "plain") {
                        return false;
                    }
                    break;
            }
        }
        return true;
    });
}

/**
 * 可见性引擎单例
 */
class VisibilityEngine {
    constructor() {
        // 单例，不需要参数
    }

    /**
     * 获取有效题目ID
     * @param {Array} ids - 题目ID数组
     * @param {Array} filters - 过滤条件数组
     * @param {Array} answers - 当前答案数组
     * @param {Object} questions - 题目对象
     * @returns {Array} 有效题目ID数组
     */
    getValidQuestionIds(ids, filters, answers, questions) {
        return getValidQuestionIds(ids, filters, answers, questions);
    }

    /**
     * 获取有效题目和答案
     * @param {Object} questions - 题目对象
     * @param {Array} answers - 当前答案数组
     * @returns {Object} 包含有效题目和答案的对象
     */
    getValidQuestionsAndAnswers(questions, answers) {
        const valid_ids = this.getValidQuestionIds(
            Object.keys(questions),
            ["visible", "plain"],
            answers,
            questions
        );
        const valid_questions = valid_ids.map(id => questions[id]);
        const valid_answers = valid_ids.map(id => answers[id]);
        return { valid_questions, valid_answers };
    }
}

// 创建单例实例
const visibilityEngine = new VisibilityEngine();

export { visibilityEngine };
